package com.heer.gymnasium.module.team.views;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.api.constants.IConstants;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.evaluate.beans.EvaTagBean;
import com.heer.gymnasium.module.my.views.MyLabelActivity;
import com.heer.gymnasium.module.team.beans.ActivityHistoryResponseBean;
import com.heer.gymnasium.module.team.beans.TeamDetailBean;
import com.heer.gymnasium.module.team.beans.TeamMemberResponseBean;
import com.heer.gymnasium.module.team.beans.TeamResponseBean;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.Session;
import com.heer.gymnasium.util.StringUtils;
import com.heer.gymnasium.util.WxShareUtils;
import com.heer.imagepick.DensityUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.qict.xinba.Util;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhihuiyun.library.commonadapter.QuickInterface;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.dialog.CommonDialog;
import com.zhihuiyun.library.dialog.TopPopWindow;
import com.zhihuiyun.library.view.MyListView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan
 * on 2018/2/12
 */

public class TeamDetailActivity extends BaseActivity {
    private static final int RES_ID_LAYOUT = R.layout.layout_team_detail;
    private static final int RES_ID_ICON = R.id.layout_team_detial_icon_iv;
    private static final int RES_ID_NAME = R.id.layout_team_detail_name_tv;
    private static final int RES_ID_CATEGORY_IV = R.id.layout_team_detail_category_iv;
    private static final int RES_ID_COUNT_IV = R.id.layout_team_detail_count_tv;
    private static final int RES_ID_LINE = R.id.layout_team_detial_line_iv;
    private static final int RES_ID_SIGN = R.id.layout_team_detial_sign_iv;
    private static final int RES_ID_TYPE = R.id.layout_team_detial_type_tv;
    private static final int RES_ID_MANIFESTO = R.id.layout_team_detial_manifesto_tv;
    private static final int RES_ID_TAG_GV = R.id.layout_team_detial_tag_gv;
    private static final int RES_ID_LIST = R.id.layout_team_detail_list_lv;
    private static final int RES_ID_MEMBER_TV = R.id.layout_team_detail_member_tv;
    private static final int RES_ID_MEMBER_LINE = R.id.layout_team_detail_member_line;
    private static final int RES_ID_HISTORY_TV = R.id.layout_team_detail_history_tv;
    private static final int RES_ID_HISTORY_LINE = R.id.layout_team_detail_history_line;
    private static final int RES_ID_MORE = R.id.layout_team_detail_open_iv;


    private static final int RES_ID_ITEM_TAG = R.layout.item_tag;
    private static final int RES_ID_ITEM_TAG_TV = R.id.text;

    private static final int RES_ID_ITEM_MEMBER = R.layout.item_team_member;
    private static final int RES_ID_ITEM_MEMBER_ICON = R.id.item_team_member_icon_iv;
    private static final int RES_ID_ITEM_MEMBER_NAME = R.id.item_team_member_name_tv;
    private static final int RES_ID_ITEM_MEMBER_COUNT = R.id.item_team_member_count_tv;
    private static final int RES_ID_ITEM_MEMBER_DETAIL = R.id.item_team_member_detial_tv;

    private static final int RES_ID_ITEM_HISTORY = R.layout.item_team_history;
    private static final int RES_ID_ITEM_HISTORY_TIME = R.id.item_team_history_time_tv;
    private static final int RES_ID_ITEM_HISTORY_TYPE = R.id.item_team_history_type_tv;
    private static final int RES_ID_ITEM_HISTORY_LOGO = R.id.item_team_history_teamlogo_iv;
    private static final int RES_ID_ITEM_HISTORY_NAME = R.id.item_team_history_teamname_iv;
    private static final int DRAWABLE_RIGHT = R.drawable.ic_dot_4_white;

    private List<String> tagData;

    private QuickTypeAdapter adapter;
    private List<TeamDetailBean.Item> itemData;
    @BindView(RES_ID_TAG_GV)
    TagFlowLayout tagGridView;
    @BindView(RES_ID_LIST)
    MyListView myListView;
    @BindView(RES_ID_MEMBER_TV)
    TextView memberTextView;
    @BindView(RES_ID_MEMBER_LINE)
    View memberLine;
    @BindView(RES_ID_HISTORY_TV)
    TextView historyTextView;
    @BindView(RES_ID_HISTORY_LINE)
    View historyLine;
    @BindView(RES_ID_MORE)
    ImageView moreImageView;
    @BindView(RES_ID_ICON)
    ImageView ivLogo;
    @BindView(RES_ID_NAME)
    TextView tvName;
    @BindView(RES_ID_CATEGORY_IV)
    ImageView ivCategory;
    @BindView(RES_ID_MANIFESTO)
    TextView tvDeclare;
    @BindView(RES_ID_COUNT_IV)
    TextView tvCount;
    @BindView(RES_ID_LINE)
    ImageView ivLine;
    @BindView(RES_ID_SIGN)
    ImageView ivSign;
    @BindView(RES_ID_TYPE)
    TextView tvType;


    private TopPopWindow topPopWindow;

    private TeamDetailActivity $this;

    private final static int LIST_TYPE_MEMBER = 0;
    private final static int LIST_TYPE_HISTORY = 1;
    private int listType = LIST_TYPE_MEMBER;//0成员，1历史
    private String tid;//战队id
    private TagAdapter<EvaTagBean> tagAdapter;
    private List<EvaTagBean> tagList;
    private int d5;

    private int pageNo = 1;
    private String captainId;

    private final int REQUEST_CODE_EDIT = 0x3;
    private final int REQUEST_CODE_MEMBER = 0x7;

    public static void startActivity(Activity context, int requestCode, String teamId) {
        Intent intent = new Intent(context, TeamDetailActivity.class);
        intent.putExtra(EXTRA_ID, teamId);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startActivity(Activity context, String teamId) {
        Intent intent = new Intent(context, TeamDetailActivity.class);
        intent.putExtra(EXTRA_ID, teamId);
        context.startActivity(intent);
    }


    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(RES_ID_LAYOUT);
        d5 = DensityUtils.dip2px($this, 5);
        tid = getIntent().getStringExtra(EXTRA_ID);
        tagList = new ArrayList<>();
        tagAdapter = new TagAdapter<EvaTagBean>(tagList) {
            @Override
            public View getView(FlowLayout parent, int position, EvaTagBean evaTagBean) {
                TextView textView = new TextView($this);
                textView.setText(evaTagBean.getName());
                if (evaTagBean.isSelect()) {
                    textView.setTextColor(getResources().getColor(R.color.coloryellow));
                    textView.setBackgroundResource(R.drawable.yellow_border);
                } else {
                    textView.setTextColor(getResources().getColor(R.color.white));
                    textView.setBackgroundResource(R.drawable.yellow_button_small);
                }
                textView.setPadding(d5,0,d5,0);
                return textView;
            }
        };
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("战队详情");
        titleUtils.setRightImage(DRAWABLE_RIGHT, 25);
        titleUtils.setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTopRightPopMenu();
            }
        });
        tagData = new ArrayList<>();
        itemData = new ArrayList<>();
        tagGridView.setAdapter(tagAdapter);
        adapter = new QuickTypeAdapter(this, itemData) {
            @Override
            public void bindData4View(ViewHolder holder, QuickInterface data, int type, int pos) {
                if (type == LIST_TYPE_MEMBER) {
                    final TeamDetailBean.Item bean = (TeamDetailBean.Item) data;
                    holder.setImg($this, RES_ID_ITEM_MEMBER_ICON, bean.getIconUrl());
                    holder.setText(RES_ID_ITEM_MEMBER_NAME, bean.getName());
                    holder.setText(RES_ID_ITEM_MEMBER_COUNT, bean.getActionCount());
                    holder.getParentView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MyLabelActivity.startActivity(context, bean.getId(), tid);
                        }
                    });
                } else {
                    final TeamDetailBean.Item bean = (TeamDetailBean.Item) data;
                    holder.setImg($this, RES_ID_ITEM_HISTORY_LOGO, bean.getIconUrl());
                    holder.setText(RES_ID_ITEM_HISTORY_NAME, bean.getName());
                    holder.setText(RES_ID_ITEM_HISTORY_TIME, StringUtils.getPhpDateFormat(bean.getTime(), new SimpleDateFormat("yyyy年MM月dd日")));
                    if (bean.getBattleType().equals(1)) {
                        holder.setText(RES_ID_ITEM_HISTORY_TYPE, "应战");
                    } else {
                        holder.setText(RES_ID_ITEM_HISTORY_TYPE, "发起约战");
                    }
                }
            }
        };
        adapter.addType(LIST_TYPE_MEMBER, RES_ID_ITEM_MEMBER).addType(LIST_TYPE_HISTORY, RES_ID_ITEM_HISTORY);
        myListView.setAdapter(adapter);
        getCorpsInfo();
        setMemberData(false);
    }

    /**
     * 显示右上角popup菜单
     */
    private void showTopRightPopMenu() {
        if (topPopWindow == null) {
            ArrayList<String> list = new ArrayList<>();
            list.add("分享战队");
            list.add("编辑战队");
            list.add("成员管理");
            list.add("退出战队");
            //(activity,onclicklistener,width,height)
            topPopWindow = new TopPopWindow($this, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0:
                            if (!TextUtils.isEmpty(tid)) {
                                WxShareUtils wxShareUtils = new WxShareUtils($this);
                                wxShareUtils.wxShare(tid, Type.SHARE_TEAM);
                            } else {
                                ToastUtil.show($this, "信息异常");
                            }
                            break;
                        case 1:
                            if (!TextUtils.equals(captainId, Session.getUserId())) {
                                DialogUtils.showDialog($this, "", "该功能仅允许队长进行操作", "", "", DialogUtils.DIALOG_TYPE_SINGLE, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtils.dismissDialog();
                                    }
                                });
                            } else {
                                CreateTeamActivity.startActivity($this, REQUEST_CODE_EDIT, tid);
                            }
                            break;
                        case 2:
                            if (!TextUtils.equals(captainId, Session.getUserId())) {
                                DialogUtils.showDialog($this, "", "该功能仅允许队长进行操作", "", "", DialogUtils.DIALOG_TYPE_SINGLE, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtils.dismissDialog();
                                    }
                                });
                            } else {
                                MemberManageActivity.startActivity($this, tid, captainId, REQUEST_CODE_MEMBER);
                            }
                            break;
                        case 3:
                            if (!TextUtils.equals(captainId, Session.getUserId())) {
                                DialogUtils.showDialog($this, "", "确认退出该战队?", "", "", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtils.dismissDialog();
                                        if (v.getId() == CommonDialog.RES_ID_POSITIVE) {
                                            quitTeam();
                                        }
                                    }
                                });
                            } else {
                                DialogUtils.showDialog($this, "", "队长不能退出战队,请先将队长权限移交给其他队员", "", "", DialogUtils.DIALOG_TYPE_SINGLE, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogUtils.dismissDialog();
                                    }
                                });
                            }
                            break;
                    }
                    topPopWindow.dismiss();
                }
            }, list, DensityUtils.dip2px($this, 200), DensityUtils.dip2px($this, 200));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            topPopWindow.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        topPopWindow.dismiss();
                    }
                }
            });
        }
        //设置默认获取焦点
        topPopWindow.setFocusable(true);
        //以某个控件的x和y的偏移量位置开始显示窗口
        topPopWindow.showAsDropDown(titleUtils.getRightView(), 0, DensityUtils.dip2px($this, 10));
        //如果窗口存在，则更新
        topPopWindow.update();
    }

    private void quitTeam() {
        mAppHelper.apiService().quitCorps(tid).enqueue(new BaseCallback<ApiResponse<Object>>() {
            @Override
            public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                ToastUtil.show($this, response.body().getMsg());
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    @OnClick({RES_ID_MEMBER_TV, RES_ID_HISTORY_TV, RES_ID_MORE})
    public void onClick(View view) {
        switch (view.getId()) {
            case RES_ID_MEMBER_TV:
                memberTextView.setTextColor(getResources().getColor(R.color.black));
                historyTextView.setTextColor(getResources().getColor(R.color.black_30_transparent));
                memberLine.setBackgroundResource(R.color.coloryellow);
                historyLine.setBackgroundResource(R.color.transparent);
                listType = LIST_TYPE_MEMBER;
                setMemberData(false);
                break;
            case RES_ID_HISTORY_TV:
                memberTextView.setTextColor(getResources().getColor(R.color.black_30_transparent));
                historyTextView.setTextColor(getResources().getColor(R.color.black));
                memberLine.setBackgroundResource(R.color.transparent);
                historyLine.setBackgroundResource(R.color.coloryellow);
                listType = LIST_TYPE_HISTORY;
                setHistoryData(false);
                break;
            case RES_ID_MORE:
                if (listType == LIST_TYPE_MEMBER) {
                    setMemberData(true);
                } else {
                    setHistoryData(true);
                }
                break;
        }
    }


    private void setMemberData(boolean loadMore) {
        if (!loadMore) {
            pageNo = 1;
            itemData.clear();
        }
        getCorpsMemberList();
    }

    /**
     *
     */
    private void setHistoryData(boolean loadMore) {
        if (!loadMore) {
            pageNo = 1;
            itemData.clear();
        }
//        adapter.notifyDataSetChanged();
        getMatchActivityHistory();
    }

    private void getCorpsInfo() {
        mAppHelper.apiService().getCorpsInfo(tid).enqueue(new BaseCallback<ApiResponse<TeamResponseBean.Info>>() {
            @Override
            public void onSuccess(Call<ApiResponse<TeamResponseBean.Info>> call, Response<ApiResponse<TeamResponseBean.Info>> response) {
                TeamDetailBean bean = TeamDetailBean.dataChange(response.body().getData());
                ImageUtil.loadUrl($this, bean.getIconUrl(), DRAWABLE_DEFAULT_LOGO, ivLogo);
                ImageUtil.loadUrl($this, bean.getCatogery(), DRAWABLE_SMALL_BASKETBALL, ivCategory);
                tvName.setText(bean.getName());
                tvDeclare.setText(bean.getManifesto());
                tvCount.setText(bean.getActionCount());
                captainId = bean.getCaptainId();
                switch (bean.getTeamType()) {
                    case 1:
                        tvType.setText("白金战队");
                        ivLine.setBackgroundResource(R.drawable.ic_platinum_line);
                        ivSign.setBackgroundResource(R.drawable.ic_team_platinum);
                        break;
                    case 2:
                        tvType.setText("黄金战队");
                        ivLine.setBackgroundResource(R.drawable.ic_gold_line);
                        ivSign.setBackgroundResource(R.drawable.ic_team_gold);
                        break;
                    case 3:
                        tvType.setText("白银战队");
                        ivLine.setBackgroundResource(R.drawable.ic_silver_line);
                        ivSign.setBackgroundResource(R.drawable.ic_team_silver);
                        break;
                    default:
                        tvType.setText("青铜战队");
                        ivLine.setBackgroundResource(R.drawable.ic_bronze_line);
                        ivSign.setBackgroundResource(R.drawable.ic_team_bronze);
                        break;
                }
                tagList.clear();
                List<String> tag_me = bean.getMyTags();
                if (tag_me != null) {
                    for (int i = 0; i < tag_me.size(); i++) {
                        EvaTagBean evaTagBean = new EvaTagBean();
                        evaTagBean.setName(tag_me.get(i));
                        evaTagBean.setSelect(true);
                        tagList.add(evaTagBean);
                    }
                }

                List<String> tag_other = bean.getOtherTags();
                if (tag_other != null) {
                    for (int i = 0; i < tag_other.size(); i++) {
                        EvaTagBean evaTagBean = new EvaTagBean();
                        evaTagBean.setName(tag_other.get(i));
                        tagList.add(evaTagBean);
                    }
                }
                tagAdapter.notifyDataChanged();
            }
        });
    }

    private void getCorpsMemberList() {
        mAppHelper.apiService().getCorpsMemberList(tid, String.valueOf(pageNo)).enqueue(new BaseCallback<ApiResponse<TeamMemberResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<TeamMemberResponseBean>> call, Response<ApiResponse<TeamMemberResponseBean>> response) {
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    moreImageView.setVisibility(View.GONE);
                } else {
                    moreImageView.setVisibility(View.VISIBLE);
                    pageNo++;
                }
                itemData.addAll(TeamDetailBean.getMemberList(response.body().getData().getData()));
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void getMatchActivityHistory() {
        mAppHelper.apiService().getMatchActivityHistory(tid, String.valueOf(pageNo)).enqueue(new BaseCallback<ApiResponse<ActivityHistoryResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<ActivityHistoryResponseBean>> call, Response<ApiResponse<ActivityHistoryResponseBean>> response) {
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    moreImageView.setVisibility(View.GONE);
                } else {
                    moreImageView.setVisibility(View.VISIBLE);
                    pageNo++;
                }
                itemData.addAll(TeamDetailBean.getHistoryList(response.body().getData().getData()));
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_EDIT && resultCode == RESULT_OK) {
            getCorpsInfo();
        }

        if (requestCode == REQUEST_CODE_MEMBER) {
            getCorpsInfo();
        }
    }
}
